package com.golddaymicromall.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import java.util.Map;
import java.util.Set;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.golddaymicromall.application.MyApplication;
import com.golddaymicromall.base.BaseActivity;
import com.golddaymicromall.bean.LoginInfo;
import com.golddaymicromall.util.AgentUtils;
import com.golddaymicromall.util.IsNetUtils;
import com.golddaymicromall.util.MD5;
import com.golddaymicromall.util.RopUtils;
import com.golddaymicromall.util.SPUtils;
import com.golddaymicromall.util.ServerConfig;
import com.google.common.collect.Maps;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.convert.StringConvert;
import com.lzy.okrx.RxAdapter;
import com.nispok.snackbar.Snackbar;
import com.nispok.snackbar.SnackbarManager;

import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;
import rx.android.schedulers.AndroidSchedulers;

/**
 * A login screen that offers login via email/password.
 */
public class LoginActivity extends BaseActivity {
    MyApplication Application;
    String Customerno;
    private IsNetUtils isnet;
    private EditText mEmailView;
    private EditText mPasswordView;
    private String email;
    private String password;


    LoginInfo info = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        SPUtils.put(getApplicationContext(), "flag", "1");
        setContentView(R.layout.activity_login);
        isnet = new IsNetUtils(LoginActivity.this);
        Application = new MyApplication();
        if (!isnet.IsNet()) {
            SnackbarManager.show(Snackbar.with(this).text("网络漫游中请查看是否有网").duration(1000));
        }
        mEmailView = (EditText) findViewById(R.id.email);
        mPasswordView = (EditText) findViewById(R.id.password);
        Button mSignInButton = (Button) findViewById(R.id.email_sign_in_button);

        mSignInButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {

                email = mEmailView.getText().toString();
                if (AgentUtils.isBlank(email)) {
                    showToast(R.string.login_hint_username);
                    return;
                }
                password = mPasswordView.getText().toString();
                if (AgentUtils.isBlank(password)) {
                    showToast(R.string.login_hint_password);
                    return;
                }
                if (password.length() < 6) {
                    showToast(R.string.common_password_format_warn);
                    return;
                }

                attemptLogin();
            }
        });
    }

    private void attemptLogin() {
        //获取设备ID
        String androidID = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID);
        String token = MD5.md5(email + androidID);
        SPUtils.put(getApplicationContext(), "token", "");

        Map<String, String> form = Maps.newHashMap();
        form.put("method", "rop.user.login");
        form.put("appKey", "00001");
        form.put("v", "1.0");
        form.put("format", "json");
        form.put("login", email);
        form.put("phoneid", token + "Android");
        form.put("regist", password);
        String sing = RopUtils.signString(form, "qwertyuiop");
        form.put("sign", sing);
        OkGo.post(new ServerConfig().SERVER)
                .params(form)
                .getCall(StringConvert.create(), RxAdapter.<String>create())
                .doOnSubscribe(() -> showLoading())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(result -> {
                    dismissLoading();
                    Log.e("result",result);
                    if (!"".equals(result)) {
                        JSONObject jsonObject = JSON.parseObject(result);
                        if (result.contains("errorToken") || "0".equals(result)) {
                            Toast.makeText(getApplicationContext(), "访问服务器失败,请稍后重试", Toast.LENGTH_SHORT).show();
                        } else if ("null".equals(result)) {
                            Toast.makeText(getApplicationContext(), "用户名或密码错误,请重试", Toast.LENGTH_SHORT).show();
                        } else if ("失败".equals(jsonObject.get("active").toString())) {
                            //提示对话框
                            AlertDialog.Builder builder = new AlertDialog.Builder(LoginActivity.this);
                            builder.setTitle("提示").setMessage("您的账号已在其他设备登录，请在其他设备上退出再登录").setNegativeButton("确定", new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    // TODO Auto-generated method stub
                                    dialog.dismiss();
                                }
                            }).show();
                        } else {
                            dismissLoading();
                            info = JSON.parseObject(result, LoginInfo.class);
                            SnackbarManager.show(Snackbar.with(this).text("登录成功").duration(1000));
                            //设置token，作为登录标识
                            setAlias(token + "Android");
                            SPUtils.put(LoginActivity.this, "Token", token);
                            SPUtils.put(LoginActivity.this, "Username", info.getUsername() == null ? "" : info.getUsername());
                            SPUtils.put(LoginActivity.this, "Active", info.getActive() == null ? "" : info.getActive());
                            SPUtils.put(LoginActivity.this, "Customerguid", info.getCustomerguid() == null ? "" : info.getCustomerguid());
                            SPUtils.put(LoginActivity.this, "Customerno", info.getCustomerno() == null ? "" : info.getCustomerno());
                            SPUtils.put(LoginActivity.this, "Email", info.getEmail() == null ? "" : info.getEmail());
                            SPUtils.put(LoginActivity.this, "Id", info.getId() == null ? "" : info.getId());
                            SPUtils.put(LoginActivity.this, "Lastlogindate", info.getLastlogindate() == null ? "" : info.getLastlogindate());
                            SPUtils.put(LoginActivity.this, "OrganizationId", info.getOrganizationId() == null ? "" : info.getOrganizationId());
                            SPUtils.put(LoginActivity.this, "Password", info.getPassword() == null ? "" : info.getPassword());
                            SPUtils.put(LoginActivity.this, "password1", password);
                            SPUtils.put(LoginActivity.this, "Status", info.getStatus() == null ? "" : info.getStatus());
                            SPUtils.put(LoginActivity.this, "Trandword", info.getTrandword() == null ? "" : info.getTrandword());
                            SPUtils.put(LoginActivity.this, "headImg", info.getImage() == null ? "" : info.getImage());
                            SPUtils.put(LoginActivity.this, "deptFlag", info.getFlag() == null ? "" : info.getFlag());
                            Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                            Customerno = SPUtils.get(getApplicationContext(), "Customerno", "").toString();
                            Application.attemptRiZhi(Customerno, Customerno + "登录");
                            startActivity(intent);
                            finish();

                        }
                    } else {
                        SnackbarManager.show(Snackbar.with(this).text("没有请求到数据,请稍后重试").duration(1000));
                    }
                }, throwable -> {
                    dismissLoading();
                    showError();
                    throwable.printStackTrace();
                });
    }

    private void setAlias(String mAlias) {
        String alias = mAlias;
        //调用JPush API设置Alias
        mHandler.sendMessage(mHandler.obtainMessage(MSG_SET_ALIAS, alias));
    }

    private static final int MSG_SET_ALIAS = 1001;


    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(android.os.Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_SET_ALIAS:
                    Log.d("TAG", "Set alias in handler.");
                    JPushInterface.setAliasAndTags(getApplicationContext(), (String) msg.obj, null, mAliasCallback);
                    break;
                default:
                    Log.i("TAG", "Unhandled msg - " + msg.what);
            }
        }
    };

    private final TagAliasCallback mAliasCallback = new TagAliasCallback() {

        @Override
        public void gotResult(int code, String alias, Set<String> tags) {
            String logs;
            switch (code) {
                case 0:
                    logs = "Set tag and alias success";
                    Log.i("", logs);
                    break;
                case 6002:
                    mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SET_ALIAS, alias), 1000 * 60);
                    break;
                default:
                    logs = "Failed with errorCode = " + code;
                    Log.e("", logs);
            }
        }

    };

}

